/*
 * Copyright © 2025−2026 WEI.ZHOU (Willis) (Chengdu). All rights reserved.
 *
 * THIS SOURCE CODE IS PROPRIETARY AND CONFIDENTIAL.
 * It is the exclusive property of WEI.ZHOU (Willis) and may not be
 * used, copied, distributed, or disclosed outside of WEI.ZHOU (Willis)
 * without express written permission.
 *
 * This code is provided to WEI.ZHOU (Willis) under a limited,
 * non-transferable internal license, and is for use only with the author's
 * approved purposes. No external license is granted or implied.
 *
 * Any unauthorized use, reproduction, or distribution is strictly prohibited
 * and may result in severe civil and criminal penalties.
 */

using Aore.Core.Extensions;
using Aore.Core.Filters;
using Aore.Core.Repository.EFCore;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using NLog.Web;
using System.Reflection;

namespace Aore.WebAPI;

public class Program
{

  /// <summary>
  /// Cors Config name
  /// </summary>
  private static readonly string _allowSpecificOrigins = "_AllowSpecificOrigins";
  
  public static void Main(string[] args)     
  {
    var builder = WebApplication.CreateBuilder(args);
    ConfigurationManager configuration = builder.Configuration;

    builder.Logging.AddNLog("NLog.config");
    // Add services to the container.
    
    // Add Cors Config
    builder.Services.AddCors(options =>
    {
      options.AddPolicy(_allowSpecificOrigins,
        policy =>
        {
          policy
            .WithHeaders("*")
            .WithOrigins(configuration["AllowedHosts"] ?? "*")
            .AllowAnyHeader()
            .AllowAnyMethod();
          //.AllowCredentials();  // 需要发送 Cookie 或 Authorization 头
        });
    });

    builder.Services.AddControllers(options =>
    {
      options.Filters.Add<GlobalExceptionFilter>();
    });

    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen($"{Assembly.GetExecutingAssembly().GetName().Name}.xml");

    // EF Core 初始化数据库DbContext
    builder.Services.AddDbContext<ApplicationDbContext>(configuration);
    
    // Autofac
    builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
    // Autofac容器配置
    builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
    {
      builder.Services.AddModule(containerBuilder, configuration);
    });
    
    // ============================================================================
    
    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
      app.AddSwaggerUI();
    }

    app.UseCors(_allowSpecificOrigins); 
    
    app.UseHttpsRedirection();

    app.UseAuthorization();
    
    app.MapControllers();
    
    app.Run();
  }
}